# api/register_api.py

from flask import Blueprint, request, jsonify
from sqlalchemy.exc import IntegrityError
from api.services import create_user, authenticate_user, create_access_token
from api.database import SessionLocal
from api.models import User  # 确保正确导入 User 模型
from datetime import datetime
from utils.response import success, error
from sqlalchemy import text

# 创建蓝图
register_bp = Blueprint("register", __name__)
login_bp = Blueprint("login", __name__)


# 获取数据库会话
def get_db():
    if SessionLocal is None:
        raise RuntimeError("数据库连接未初始化，请检查配置和连接状态")
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@register_bp.route("/register", methods=["POST"])
def register():
    """
    用户注册接口
    """
    # 检查请求头是否为 JSON
    if not request.is_json:
        return error(message="邮箱格式不正确")

    # 获取 JSON 数据
    data = request.json
    username = data.get("username")
    email = data.get("email")
    password = data.get("password")
    if not username or not email or not password:
        return error(message="用户名、邮箱和密码都是必填项")
    if len(password) < 6:
        return error(message="密码不能少于6个字符")
    if "@" not in email:
        return error(message="邮箱格式不正确")

    db = next(get_db())
    try:
        # 检查邮箱是否已被注册
        existing_email = db.execute(
            text("SELECT * FROM users WHERE email = :email"), {"email": email}
        ).fetchone()

        if existing_email:
            return error(message="该邮箱已被注册，请更换邮箱")
        existing_username = db.execute(
            text("SELECT * FROM users WHERE username = :username"),
            {"username": username},
        ).fetchone()

        if existing_username:
            return error(message="该用户名已被注册，请更换用户名")

        # 创建用户
        user = create_user(db, data)
        new_user = db.execute(
            text("SELECT id, username FROM users WHERE username = :username"),
            {"username": user["username"]},
        ).fetchone()

        return success(
            data={"id": new_user.id, "username": user["username"]}, message="注册成功"
        )

    except Exception as e:
        db.rollback()
        return error(message="注册失败：" + str(e))


@login_bp.route("/login", methods=["POST"])
def login():
    """
    用户登录接口
    """
    if not request.is_json:
        return error(message="请求头 Content-Type 必须为 application/json")

    data = request.get_json()
    username = data.get("username")
    password = data.get("password")

    if not username or not password:
        return error(message="用户名和密码都是必填项")

    db: Session = next(get_db())
    try:
        # 调用认证函数验证用户
        user = authenticate_user(db, username, password)
        if not user:
            return error(message="用户名或密码错误")

        # 更新登录时间 & 登录次数
        user.last_login_date = datetime.now()
        user.login_count = (user.login_count or 0) + 1
        db.commit()

        # 生成 JWT Token（可选：也可使用 session）
        access_token = create_access_token(data={"identity": user.username})

        # 返回成功响应（与注册接口一致的格式）
        return success(
            data={
                "token": access_token,
                "username": user.username,
                "id": user.id,
            },
            message="登录成功",
        )

    except Exception as e:
        db.rollback()
        return error(message="登录失败：" + str(e))
